package Core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import javax.swing.JOptionPane;

import msgParser.Parser;
import msgParser.Strings;

import GUI.MainWindow;

import tokenizer.FixedSeparatorMessageTokenizer;
import tokenizer.StringMessageTokenizer;

/*
 * Made By: Kudinov Roma
 * 2013
 * 
 */
public class ConnectionListener implements Runnable
{
	private SocketChannel sChannel;
	private StringMessageTokenizer tokenizer;
	private ByteBuffer inbuf;
	private final int NUM_OF_BYTES = 4096;
	public static final String MESSAGE_DELIMITER = "\u0001";
	
	public ConnectionListener(SocketChannel sc) throws UnsupportedEncodingException
	{
		sChannel = sc;
		inbuf = ByteBuffer.allocate(NUM_OF_BYTES); 
		tokenizer = new FixedSeparatorMessageTokenizer(MESSAGE_DELIMITER,Charset.forName("UTF-8"));
	}
	public void run()
	{
		while(true)
		{
			while (!tokenizer.hasMessage()) 
			{
				inbuf.clear();
				try 
				{
					sChannel.read(inbuf);
				} 
				catch (Exception e) 
				{
					if(!Connection.isConnected()) return;
					if(e instanceof InterruptedException) //manually interrupted by user
						return;
					Connection.disconnect();
					MainWindow.data = new SessionData();
					MainWindow.getMenu().connectionInterrupted();
					return;
				}
				inbuf.flip();
				tokenizer.addBytes(inbuf);
			}
			String msg = tokenizer.nextMessage();
			
			MainWindow.getMenu().incomingMessage(msg);
			Parser p = new Parser(msg);
			p.Parse();
			try 
			{
				if(p.testHeader(Strings.NOTIFY))
				{
					MainWindow mw = (MainWindow) MainWindow.getMenu().getFrame();
					mw.notification(p.argStr(1));
				}
			}
			catch(Exception e) 
			{
				
			}
			
		}
		
	}

}
